package com.binsoft.ndtta;

import java.text.SimpleDateFormat;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

public class FixtureListFragment extends ListFragment
{
	private static final String TAG = "FixtureListActivity";

	private int mTeam = 0;
	private int mDivision = 0;
	private int mWeek = 0;
		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		Log.i(TAG, "Creating View");
		
		// Extract the team
		mWeek = ((MainActivity)getActivity()).getCurrentWeek();
		mTeam = ((MainActivity)getActivity()).getCurrentTeam();
		mDivision = ((MainActivity)getActivity()).getCurrentDivision();
		
		setListAdapter( new FixtureAdapter( ((MainActivity)getActivity()).getDBAdapter(), getActivity(), mWeek, mDivision, mTeam ) );
		
		return super.onCreateView(inflater, container, savedInstanceState);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo)
	{
		// See if we have to display the menu or not.
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
		Match clickedMatch = (Match)getListAdapter().getItem(info.position);

		if ( ( -1 != clickedMatch.home() ) && ( -1 != clickedMatch.away() ) )
		{
			MenuInflater inflater = getActivity().getMenuInflater();
			inflater.inflate(R.menu.list_context_menu, menu);
			
			menu.setHeaderIcon(R.drawable.logo);
			menu.setHeaderTitle("Match");
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		Match clickedMatch = (Match)getListAdapter().getItem( info.position );
		//Get teams
		Team clickedHomeTeam = Matches.getTeam( clickedMatch.division(), clickedMatch.home() );
		Team clickedAwayTeam = Matches.getTeam( clickedMatch.division(), clickedMatch.away() );
		int homeScore = 0;
		int awayScore = 0;

		// Popup the score dialog.
		if ( clickedHomeTeam != null && clickedAwayTeam != null && !clickedHomeTeam.name().isEmpty() &&
				!clickedAwayTeam.name().isEmpty() )
		{
			Cursor prevMatch = ((MainActivity)getActivity()).getDBAdapter().fetchMatch( clickedMatch,false,true );
			
			if ( null != prevMatch && prevMatch.getCount() > 0 )
			{				
				int homeScoreCol = prevMatch.getColumnIndex("homescore");
				int awayScoreCol = prevMatch.getColumnIndex("awayscore");
				
				homeScore = prevMatch.getInt( homeScoreCol );
				awayScore = prevMatch.getInt( awayScoreCol );
			}
		}

		SimpleDateFormat format = new SimpleDateFormat(Constants.DATE_FORMAT);

		switch ( item.getItemId() )
		{
		case R.id.scoreContentItem:
			
		    FragmentTransaction ft = getFragmentManager().beginTransaction();
		    Fragment prev = getFragmentManager().findFragmentByTag("dialog");
		    if (prev != null) 
		    {
		        ft.remove(prev); 
		    }
		    ft.addToBackStack(null);
		    
			DialogFragment newFragment = MatchDialogFragment.newInstance(format.format( clickedMatch.date() ), info.position, mTeam, clickedHomeTeam.name(), clickedAwayTeam.name(), homeScore, awayScore );
			newFragment.show(ft, "dialog");
			break;
		case R.id.shareMenuItem:
			Intent sendIntent = new Intent( Intent.ACTION_SEND);
			sendIntent.setType("text/plain");
			StringBuilder shareText = new StringBuilder();
			shareText.append( format.format( clickedMatch.date() ) );
			shareText.append( '\n' );
			shareText.append( clickedHomeTeam.name() + " (" + homeScore + ") vs (" + 
					awayScore + ") " + clickedAwayTeam.name());			
			sendIntent.putExtra(Intent.EXTRA_TEXT, shareText.toString() );
			sendIntent.setType("text/plain");
			
			startActivity(Intent.createChooser( sendIntent, "Share the match..."));
			break;
		}

		return super.onContextItemSelected(item);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);

		// Register for a context menu.
		registerForContextMenu( getListView() );
	}
}
